package com.dai.rpc.netty.handler;

import com.dai.rpc.exceptions.MyRpcException;
import com.dai.rpc.factory.SingletonFactory;
import com.dai.rpc.message.RpcRequest;
import com.dai.rpc.server.MyServiceProvider;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyRequestHandler {

    private MyServiceProvider myServiceProvider;

    public MyRequestHandler() {
        this.myServiceProvider = SingletonFactory.getInstance(MyServiceProvider.class);
    }

    public Object handler(RpcRequest data) {

        // 获取服务
        String interfaceName = data.getInterfaceName();
        String version = data.getVersion();
        Object service = myServiceProvider.getService(interfaceName + version);
        if(service == null) throw new MyRpcException("未找到对应的服务方");

        try {
            // 掉用服务
            Method method = service.getClass().getMethod(data.getMethodName(),data.getParamTypes());
            Object result = method.invoke(service, data.getParameters());
            // 返回服务调用结果
            return result;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            System.out.println("服务出现问题：" + e.getMessage());
        }
        return null;
    }
}
